package dice_machine

import (
	"fmt"
	"log"
	"math"
	"math/rand"
	"time"
)

// 判断用户选择的掷子范围是否在区间内[1, totalnumbers]
func (i input) isValid() error {
	if i.choices <= 0 || i.choices > DcTotalNumbers {
		return fmt.Errorf("choice is not valid [1,%d]", DcTotalNumbers)
	}
	return nil
}

func NewDice(choice, betNum int, isRollDown bool, tag string) (*DiceGame, error) {
	inp := input{
		choices:    choice,
		betNum:     betNum,
		isRollDown: isRollDown,
		tag:        tag,
	}
	if err := inp.isValid(); err != nil {
		return nil, err
	}
	return &DiceGame{i: &inp, R: &result{Odds: 0}}, nil
}

// 计算赔率
func (d DiceGame) calOdds() {
	d.R.Odds = float64(DcTotalNumbers) / float64(d.i.choices)
	if !d.i.isRollDown {
		d.R.Odds = float64(DcTotalNumbers) / float64(DcTotalNumbers-d.i.choices)
	}
	d.R.Odds = math.Round(d.R.Odds*10000) / 10000
	d.R.Odds *= 0.99 //赔付金额收取百分之1作为手续费
}

// 掷子
func (d DiceGame) roll() {
	rand.Seed(time.Now().UnixNano())
	//[1-101)=[1-100]
	d.R.RollNum = rand.Intn(DcTotalNumbers) + 1
}

// 计算奖金
func (d DiceGame) calReward() {
	d.R.IsReward = d.R.RollNum <= d.i.choices
	if !d.i.isRollDown {
		d.R.IsReward = d.R.RollNum >= d.i.choices
	}

	if d.R.IsReward {
		d.R.RewardNum = int(float64(d.i.betNum) * d.R.Odds) //只取整数
	}
}

func (d DiceGame) ToString() {
	log.Printf("%+v", d.R)
	log.Printf("%+v", d.i)
}

func (d DiceGame) Before(handler UserHandler) error {
	return handler.Check(d.i)
}

func (d DiceGame) After(handler UserHandler) error {
	return handler.ChangeBalance(d.i, d.R)
}

// Play 玩游戏
func (d DiceGame) Play() {
	d.calOdds()
	d.roll()
	d.calReward()
}
